package com.example.usb.util;

import android.Manifest;

import com.example.usb.MyApplication;
import com.example.usb.R;
import com.lib.uvccamera.utils.DebugLog;
import com.yanzhenjie.permission.AndPermission;

/**
 * created by liangkun on ${DATA}
 * Describe:权限申请工具类
 */

public class PermissionUtil {
  public static String permission ="Permission";
    //
    public static String[] permissions = new String[]{
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.CAMERA,
    };

    /**
     * 获取权限数据
     *
     * @param permissionListener 权限监听
     */
    public static void requestPermission( PermissionListener permissionListener) {
        AndPermission.with(MyApplication.getContext())
                .permission(PermissionUtil.permissions)
                // 准备方法，和 okhttp 的拦截器一样，在请求权限之前先运行改方法，已经拥有权限不会触发该方法
                .rationale((context, permissions, executor) -> {
                    // 此处可以选择显示提示弹窗
                    executor.execute();
                    for (int i = 0; i < permissions.size(); i++) {
                        DebugLog.d(DebugLog.LOGHsc + " 没给permission " + permissions.get(i));
                    }
                })
                // 用户给权限了
                .onGranted(permissions ->
                        //权限申请完开启所有任务
                        permissionListener.onGranted()
                )
                // 用户拒绝权限，包括不再显示权限弹窗也在此列
                .onDenied(permissions -> {
                    permissionListener.onDenied(permissions);
                    // 判断用户是不是不再显示权限弹窗了，若不再显示的话进入权限设置页
                    if (AndPermission.hasAlwaysDeniedPermission(MyApplication.getContext(), permissions)) {
                        for (int i = 0; i < permissions.size(); i++) {
                            String permission = permissions.get(i);
                            DebugLog.d(DebugLog.LOGHsc + " permission " + permission);
                            switch (permission) {
                                case Manifest.permission.WRITE_EXTERNAL_STORAGE:
                                case Manifest.permission.READ_EXTERNAL_STORAGE:
                                    ToastUtil.toastShortContent(MyApplication.getContext().getResources().getString(R.string.please_external_permission));
                                    AndPermission.permissionSetting(MyApplication.getContext()).start();
                                    break;
                            }
                        }
                    }

                }).start();
    }
}
